const compressing = require('compressing');
const axios = require('axios');
const fs = require('fs-extra');
const FormData = require("form-data");

const config = {
  // base: `D:\\work\\uz\\小组工作\\930应用\\APICloud助手930`,
  // base:'D:\\work\\uz\\小组工作\\930应用\\问卷调查',
  base: `C:/Users/zhutianhao/Desktop/meeting-order-rotate`,//第一步，该本机电脑要上传的文件
  // base:'/Users/YangYongAn/Work/case/yonstore_mobile_mx',
  // base:'/Users/YangYongAn/Desktop/点餐-0322',
  // base: '/Users/YangYongAn/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9/815368862608932b0ab194f63d956880/Message/MessageTemp/d4a46b4cea5543b745c0e736b24210f6/File/14d486c4b01a2acf9163784f67ac38af',
  isAVM: true,
  evn: 'prod',
  autoClean: true,
}


const evn = {
  daily: {
    host: 'https://openapi-u8c-daily.yyuap.com/',
    // resourceid: '20211018161532613-1142',
    resourceid: '20210816195457122-0917',
    user: {
      account: 'apiCloud',
      password: 'apiCloud'
    }
  },
  pre: {
    host: 'https://openapi-yonsuite-pre.diwork.com/',
    resourceid: '20211018161904073-2091',
    user: {
      account: '-',
      password: '-'
    }
  },
  prod: {
    host: 'https://openapi.yonyoucloud.com/',
    resourceid: '20211020145044630-3532',// APICloud
    // resourceid:'20211020145109293-6035',// 调查问卷
    // resourceid:'20211020145133668-3829',// 活动助手
    user: {
      account: 'apicloud',
      password: 'apicloud'
    }
  }
}


console.log(`[0/5 开始运行] 当前环境 ${config.evn}`);

const dest = 'update__' + new Date().getTime() + '.zip';


const { host, resourceid, user } = evn[config.evn];

(async () => {
  const tempDir = './temp';
  if (config.isAVM) {
    console.log(`[1/5 AVM准备] 当前isAVM ${config.isAVM}`);

    await fs.emptyDirSync(tempDir);

    try {
      await fs.copy(config.base, tempDir);

      for (const dir of ['.apicloud', '.svn', '.vscode', '.idea', 'pages', 'components']) {
        await fs.removeSync(tempDir + '/' + dir)
      }

      try {
        fs.renameSync(`${tempDir}/.bin`, `${tempDir}/pages`);
      } catch (e) {
        if (e.errno === -4058) {
          return console.log(`请先执行友空间预览生成 .bin 文件`)
        } else {
          console.log(`重命名错误`, e)
        }
      }
    } catch (err) {
      console.error(err)
    }

  } else {
    console.log(`[1/5 代码提取] 当前isAVM ${config.isAVM}`);
    await fs.emptyDirSync(tempDir);
    await fs.copy(config.base, tempDir);


    await fs.copy(config.base, tempDir);
    ['.apicloud', '.svn', '.vscode', '.idea', 'pages', '.git', 'components'].forEach(async dir => {
      await fs.removeSync(tempDir + '/' + dir)
    });


  }


  console.log(`[2/5 开始压缩] 文件名称 ${dest}`)
  // 压缩项目为zip
  await compressing.zip.compressDir(tempDir, dest, { ignoreBase: true });

  const { size } = await fs.statSync(dest);

  console.log(`[3/5 完成压缩] 文件大小 ${(size / 1024).toFixed(2)}kb 开始上传`);


  const { token } = await axios.post(`${host}esn-resource/rest/user/login`, user).then(r => r.data).then(data => {
    if (data.error_code === '0') {
      return data.data;
    } else {
      console.error(`鉴权登录失败:${data.error_description}`)
    }
  })


  const form = new FormData();
  form.append("file", await fs.createReadStream(dest));

  const { data: zipurl } = await axios({
    method: "post",
    url: `${host}esn-resource/rest/resource/record/upload?token=${token}`,
    data: form,
    headers: form.getHeaders()
  }).then(v => v.data).then(data => {
    if (data.error_code === '0') {
      return data;
    } else {
      console.error(`上传失败:${data.error_description}`)
    }
  }).catch(e => console.error(`上传出错:${e}`))


  console.log(`[4/5 上传成功] 正在保存 远程路径 ${zipurl}`)
  const saveRes = await axios.post(`${host}esn-resource/rest/resource/record/save?token=${token}`, {
    resourceid,
    "version": "DEFAULT_VERSION",
    "remark": "[AUTO]" + dest,
    "records": [{ zipurl, "zipPath": "", "type": "Android" }, { zipurl, "zipPath": "", "type": "ios" }]
  }).then(v => v.data)


  console.log(`[5/5 保存成功] 请刷新友空间查看`);

  config.autoClean && fs.rmSync(dest);

})()


